const app = getApp();

Page({
    data: {
        active: 0,
        completedConsultations: [],
        uncompletedConsultations: [],
        user:null
    },
    onLoad: function () {
        this.fetchConsultationData();
    },
    navigateBack() {
        wx.navigateBack(); // 返回上一页
    },
    onTabChange(e) {
        this.setData({
            active: e.detail.index
        });
    },
    onLoadMoreCompleted() {
        this.fetchMoreData('completed');
    },
    onLoadMoreUncompleted() {
        this.fetchMoreData('uncompleted');
    },
    fetchConsultationData() {
        const userId = app.globalData.user.id; // 从全局变量中获取 userId
        wx.request({
            url: `http://localhost:8080/hql/booking/user`,

            method: 'GET',
            data: {
                userId: userId
            },
            header: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + app.globalData.user.token // 在请求头中
            },
            success: (res) => {

                if (res.statusCode === 200 && res.data.code === 200) {
                    console.log('zixun',res);
                    const data = res.data.data || [];
                    const completed = data.filter(item => item.isCompleted).map(item => this.formatTime(item));
                    const uncompleted = data.filter(item => !item.isCompleted).map(item => this.formatTime(item));
                    
                    app.globalData.completedConsultations = completed;
                    app.globalData.uncompletedConsultations = uncompleted;
                    
                    this.setData({
                        completedConsultations: completed,
                        uncompletedConsultations: uncompleted,
                        user: app.globalData.user
                    });
                } else {
                    console.error('获取数据失败:', res);
                    wx.showToast({
                        title: '获取数据失败',
                        icon: 'none'
                    });
                }
            },
            fail: (err) => {
                console.error('请求失败:', err);
                wx.showToast({
                    title: '网络请求失败',
                    icon: 'none'
                });
            }
        });
    },
    fetchMoreData(type) {
        const userId = app.globalData.userId;
        wx.request({
            url: `${app.globalData.baseUrl}/booking/user/more`,
            method: 'GET',
            data: {
                userId: userId,
                type: type
            },
            header: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + app.globalData.user.token // 在请求头中
            },
            success: (res) => {
                if (res.statusCode === 200 && res.data.code === 200) {
                    const newItems = res.data.data || [];
                    let globalDataKey, setDataKey, newItemsFormatted;
                    
                    if (type === 'completed') {
                        newItemsFormatted = newItems.filter(item => item.isCompleted).map(item => this.formatTime(item));
                        globalDataKey = 'completedConsultations';
                        setDataKey = 'completedConsultations';
                    } else {
                        newItemsFormatted = newItems.filter(item => !item.isCompleted).map(item => this.formatTime(item));
                        globalDataKey = 'uncompletedConsultations';
                        setDataKey = 'uncompletedConsultations';
                    }
                    
                    app.globalData[globalDataKey] = [...app.globalData[globalDataKey], ...newItemsFormatted];
                    this.setData({
                        [setDataKey]: app.globalData[globalDataKey]
                    });
                } else {
                    wx.showToast({
                        title: type === 'completed' ? '没有更多已完成咨询' : '没有更多未完成咨询',
                        icon: 'none'
                    });
                }
            },
            fail: (err) => {
                console.error('请求失败:', err);
                wx.showToast({
                    title: '网络请求失败',
                    icon: 'none'
                });
            }
        });
    },
    formatTime(item) {
        // 将时间字符串转换为Date对象
        const bookingTime = new Date(item.bookingTime);
        const estimatedEndTime = new Date(item.estimatedEndTime);
        
        // 格式化时间为 "YYYY-MM-DD HH:MM" 格式
        const formatBookingTime = `${bookingTime.getFullYear()}-${String(bookingTime.getMonth() + 1).padStart(2, '0')}-${String(bookingTime.getDate()).padStart(2, '0')} ${String(bookingTime.getHours()).padStart(2, '0')}:${String(bookingTime.getMinutes()).padStart(2, '0')}`;
        const formatEstimatedEndTime = `${estimatedEndTime.getFullYear()}-${String(estimatedEndTime.getMonth() + 1).padStart(2, '0')}-${String(estimatedEndTime.getDate()).padStart(2, '0')} ${String(estimatedEndTime.getHours()).padStart(2, '0')}:${String(estimatedEndTime.getMinutes()).padStart(2, '0')}`;
        
        // 返回新的对象，包含格式化后的时间
        return {
            ...item,
            bookingTime: formatBookingTime,
            estimatedEndTime: formatEstimatedEndTime
        };
    }
});